/**
 *
 */
package hichecker.ui.components.file_chooser;

import hichecker.ui.components.file_chooser.file_filter.AbstractFileFilter;
import hichecker.ui.components.file_chooser.file_filter.MainFileFilter;
import hichecker.ui.components.file_chooser.file_filter.PartFileFilter;

import java.io.File;

import javax.swing.JFileChooser;

import org.apache.log4j.Logger;

/**
 *
 */
public abstract class AbstractFileChooser extends JFileChooser {
	private Logger logger = Logger.getLogger(AbstractFileChooser.class);

	public enum FileType {MAIN, PART}

	public AbstractFileChooser(FileType type, String title) {
		super();
		setDialogTitle(title);

        // Delete entry "All files"
        removeChoosableFileFilter(getChoosableFileFilters()[0]);

        // Sets the FileFilter
		switch (type) {
		case MAIN:
			setFileFilter(new MainFileFilter());
			break;
		case PART:
			setFileFilter(new PartFileFilter());
			break;
		default:
			logger.error("Unspecified FileType");
		}
	}

	/**
	 * Returns the selected file with the validated name
	 *
	 * @see #validateFileName
	 */
	@Override
	public File getSelectedFile() {
		return validateFileName(super.getSelectedFile());
	}

	/**
	 * Checks if a select file has the neccessary extension and adds it if not
	 *
	 * @param file
	 * @return
	 */
	private File validateFileName(File file) {
		// null check file: nothing to do
		if (file == null)
			return file;
		// null check filefilter
		if (getFileFilter() == null) {
			logger.error("The FileFilter is null.");
			return file;
		}

		// Cast current FileFilter to AbstractFileFilter
		if (!(getFileFilter() instanceof AbstractFileFilter)) {
			logger.error("Can't cast " + getFileFilter().getClass().getName()
					+ " to AbstractFileFilter.");
			return file;
		}
		AbstractFileFilter fileFilter = (AbstractFileFilter) getFileFilter();

		// correct extension, return file
		if (file == null || fileFilter.accept(file))
			return file;

		// add missing extension
		String fileName = file.getName();
		fileName += "." + fileFilter.getExtension();

		return new File(file.getParent(), fileName);

	}

}